<template>
  <CloudDialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-open="handleOpen"
    :before-close="handleClose">
    <a-form ref="formRef" layout="vertical" :rules="rules" :model="formState">
      <a-form-item
        label="域名"
        field="name"
        asterisk-position="end"
        hide-asterisk>
        <a-input v-model="formState.name" placeholder="请输入域名"></a-input>
      </a-form-item>
      <a-form-item
        label="DNS API名称"
        field="dns_api_id"
        asterisk-position="end"
        hide-asterisk>
        <a-select
          v-model="formState.dns_api_id"
          :options="dnsNameOptions"
          placeholder="请选择DNS API名称"></a-select>
      </a-form-item>

      <a-form-item label="备注" field="remark" asterisk-position="end">
        <a-textarea
          v-model="formState.remark"
          :max-length="200"
          show-word-limit
          :auto-size="{ maxRows: 3, minRows: 3 }"
          placeholder="请输入备注"></a-textarea>
      </a-form-item>
    </a-form>
  </CloudDialog>
</template>
<script lang="ts" setup>
import type { DomainItem } from '@/apis/model/resolve'
import { getApiResolveDnsApisApi } from '@/apis/modules/resolve/dns'
import {
  addApiResolveDomainApi,
  updateApiResolveDomainApi
} from '@/apis/modules/resolve/domain'
import {
  Message,
  type FieldRule,
  type FormInstance
} from '@arco-design/web-vue'
interface IProp {
  record?: DomainItem
}
const visible = defineModel<boolean>('visible', { required: true })
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits(['reload'])
const title = computed(() => (props.record?.id ? '编辑域名' : '添加域名'))
const formRef = ref<FormInstance>()
const dnsNameOptions = ref<LabelValue[]>([])
const formState = ref({
  name: '',
  dns_api_id: '',
  remark: ''
})

const rules: Record<string, FieldRule> = {
  name: {
    required: true,
    validator(value, callback) {
      const reg =
        // eslint-disable-next-line no-useless-escape
        /^(?=^.{3,253}$)(?!((.*((--)|(\.-)|(-\.))[^\.])|(^-.*)))([a-zA-Z0-9\-_]{1,63}?\.)+[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/
      if (!value) {
        callback('请输入域名')
        return
      }
      if (!reg.test(value)) {
        callback('域名格式不正确')
        return
      }
      callback()
    }
  },
  dns_api_id: { required: true, message: '请选择 DNS API 名称' }
}

const handleOpen = async () => {
  try {
    const res = await getApiResolveDnsApisApi({ limit: 0 })
    const list = res.list ?? []

    dnsNameOptions.value = list
      .map((item) => ({ label: item.name!, value: item.id! }))
      .filter(Boolean)
  } catch (error) {
    console.error(error)
  }
  if (props.record) {
    formState.value.dns_api_id = props.record.dns_api_id!
    formState.value.name = props.record.name!
    formState.value.remark = props.record.remark!
  }
}
const handleSubmit = async () => {
  const error = await formRef.value?.validate()
  if (error) return false

  const fn = props.record ? updateApiResolveDomainApi : addApiResolveDomainApi
  const msg = props.record ? '修改成功' : '添加成功'
  const data = props.record
    ? { id: props.record.id!, ...formState.value }
    : formState.value
  return fn(data).then(() => {
    Message.success(msg)
    emit('reload')
  })
}

const handleClose = () => {
  formRef.value?.resetFields()
}
</script>
